package com.sdy.mvc.config;

import com.sdy.mvc.feign.FeignSpringBodyDecoder;
import com.sdy.mvc.feign.FeignSpringBodyEncoder;
import com.sdy.mvc.feign.FeignSpringErrorDecoder;
import com.sdy.mvc.feign.RpcBodyContract;
import com.sdy.mvc.feign.RpcServlet;
import feign.Contract;
import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.codec.ErrorDecoder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfig {
    public static final String RPC_URL_PREFIX = "_remote_procedure_call";
    @Value("${inner_token:}")
    private String innerToken;
    
    @Bean
    public Contract contract() {
        return new RpcBodyContract();
    }
    
    @Bean
    public Encoder feignSpringBodyEncoder() {
        return new FeignSpringBodyEncoder();
    }

    @Bean
    public Decoder feignSpringBodyDecoder() {
        return new FeignSpringBodyDecoder();
    }

    @Bean
    public ErrorDecoder feignSpringErrorDecoder() {
        return new FeignSpringErrorDecoder();
    }
    
    @Bean
    public ServletRegistrationBean rpcServletRegistrationBean(ApplicationContext applicationContext) {
        ServletRegistrationBean<RpcServlet> s = new ServletRegistrationBean<>(new RpcServlet(applicationContext, innerToken), "/".concat(FeignConfig.RPC_URL_PREFIX).concat("/*"));
        s.setLoadOnStartup(1);
        return s;
    }
}
